from pyecharts import options as opts
from pyecharts.charts import Funnel
from pyecharts.commons.utils import JsCode
import pandas as pd

def get_model_manufacturer_top10_data(df):
    try:
        df_clean = df.copy()
        df_clean['销量'] = pd.to_numeric(df_clean['销量'], errors='coerce')
        df_clean = df_clean.dropna(subset=['厂商', '车型', '销量'])

        manufacturer_sales = df_clean.groupby('厂商')['销量'].sum().reset_index()
        top_manufacturers = manufacturer_sales.nlargest(10, '销量')['厂商'].tolist()

        charts = {}

        for manufacturer in top_manufacturers:
            manufacturer_data = df_clean[df_clean['厂商'] == manufacturer]
            top_models = (
                manufacturer_data.groupby('车型')
                .agg({'销量': 'max'})
                .reset_index()
                .nlargest(10, '销量')
            )

            funnel_data = [(row['车型'], row['销量']) for _, row in top_models.iterrows()]

            funnel = (
                Funnel()
                .add(
                    series_name=manufacturer,
                    data_pair=funnel_data,
                    sort_="descending",
                    label_opts=opts.LabelOpts(position="inside"),
                    itemstyle_opts=opts.ItemStyleOpts(border_color="#fff"),
                )
                .set_global_opts(
                    title_opts=opts.TitleOpts(
                        title=f"{manufacturer} Top 10 Models",
                        subtitle="销量",
                        pos_left="center",
                        pos_top="10px",
                    ),
                    legend_opts=opts.LegendOpts(
                        pos_top="50px",
                        pos_left="right",
                        orient="vertical",
                    ),
                    tooltip_opts=opts.TooltipOpts(
                        trigger="item",
                        formatter=JsCode(
                            "function (params) {return params.seriesName + '<br/>' + params.name + ': ' + params.value;}"
                        )
                    ),
                )
            )

            charts[manufacturer] = funnel.dump_options_with_quotes()

        return {
            'success': True,
            'charts': charts,
            'manufacturers': top_manufacturers
        }

    except Exception as e:
        return {
            'success': False,
            'error': f'处理数据时出错: {str(e)}'
        }
